package com.example.springsecurity.enums;

import com.example.springsecurity.exception.MySecurityException;
import lombok.Data;
import lombok.Getter;
import lombok.Setter;

import java.text.MessageFormat;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author wuancheng
 * @date 2024/6/21 9:37
 * @description 错误码
 */
@Getter
public enum ErrorCode {
    /**
     * 基础异常从1000-1999
     */
    ERROR_CODE_UNDEFINED("SS-1000", "错误码未定"),
    SYSTEM_ERROR("SS-1001", "系统错误"),
    PARAM_CANNOT_EMPTY("SS-1002","参数{0}不能为空"),
    PARAMS_FORMAT_ERROR("SS-1003", "参数{0}格式错误"),
    SERVICE_UNAVAILABLE("SS-1004", "当前服务暂不可用，请稍后再试"),
    SERVICE_NETWORK_CONNECT_FAIL("SS-1005","服务调用网络连接失败"),
    NO_LOGIN("SS-1006", "登录失效，请重新登录"),
    NO_PERMISSION("SS-1007", "没有权限访问"),

    /**
     * 登录异常
     */
    TOKEN_PARSE_ERROR("SS-2001", "token解析异常"),
    TOKEN_EXPIRE_ERROR("SS-2002", "token过期"),
    LOGIN_FAIL("SS-2003", "登录失效，请重新登录"),
    ;

    /**
     * 错误码
     */
    private String errorCode;

    /**
     * 错误描述
     */
    private String errorDesc;

    ErrorCode(String errorCode, String errorDesc) {
        this.errorCode = errorCode;
        this.errorDesc = errorDesc;
    }

    private static Map<String, ErrorCode> errorCodeMap = new ConcurrentHashMap<>();

    static {
        ErrorCode[] values = ErrorCode.values();
        for (ErrorCode value : values) {
            ErrorCode errorCode = errorCodeMap.get(value.getErrorCode());
            if (errorCode != null) {
                System.err.println("==============错误码重复==============:" + value.getErrorCode());
            } else {
                errorCodeMap.put(value.getErrorCode(), value);
            }
        }
    }

    public static ErrorCode getErrorCode(String errorCode) {
        ErrorCode code = errorCodeMap.get(errorCode);
        if (code == null) {
            return ErrorCode.ERROR_CODE_UNDEFINED;
        }
        return code;
    }

    public MySecurityException getMySecurityException(){
        return new MySecurityException(getErrorCode(), getErrorDesc());
    }

    public MySecurityException getMySecurityException(Object ... param){
        return new MySecurityException(getErrorCode(), MessageFormat.format(getErrorDesc(), param));
    }
}

